<script setup lang="ts">
import type { EChartsCoreOption } from '#/hooks';

import { nextTick, onBeforeUnmount, onMounted, shallowRef, watch } from 'vue';

import { useEcharts } from '#/hooks';

interface Props {
  options: EChartsCoreOption;
}
const props = defineProps<Props>();
const elEcharts = shallowRef();
//  监听图表dom
let observer: null | ResizeObserver = null;
const currentOptions = shallowRef(props.options);
const { setOptions, initCharts, echartsResize, destroyCharts } = useEcharts(
  elEcharts,
  currentOptions.value,
);

//  监听响应式options以便监听变化，但设置时传递普通对象
watch(
  () => props.options,
  (nVal) => {
    const targetOptions: EChartsCoreOption = { ...nVal };
    setOptions(targetOptions);
  },
  {
    deep: true,
  },
);

const handleResize = (_entries: any) => {
  echartsResize();

  // 这里可以执行针对宽高变化的操作
  // for (const entry of entries) {
  //   const { width, height } = entry.contentRect
  // }
};
onMounted(() => {
  // 防止图表dom宽高继承自父容器时，父容器宽高是涉及到百分比或相对定位的情况未及时传递，导致宽高为0
  nextTick(() => {
    initCharts();
  });
  observer = new ResizeObserver(handleResize);
  observer.observe(elEcharts.value);
});
onBeforeUnmount(() => {
  observer?.disconnect();
  destroyCharts();
});
</script>
<template>
  <!-- 继承父容器宽高，容器大小由外部父容器给定 -->
  <div style="width: 100%; height: 100%" ref="elEcharts"></div>
</template>
